package com.easy.web.utils;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 对象操作基本方法
 * 
 * @author Jimmy
 * 
 */
public class BeanUtils {

	private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);

	public static void copyNotNull(Object src, Object dest) {
		baseCopy(src, dest, false);
	}

	public static void copy(Object src, Object dest) {
		baseCopy(src, dest, true);
	}

	public static void baseCopy(Object src, Object dest, boolean isCopyNull) {
		Map<String, Field> objMap = getObjectAllField(src, true);
		Map<String, Field> destMap = getObjectAllField(dest, true);
		Set<String> objFieldNameSet = objMap.keySet();
		Field objField = null;
		Field descField = null;
		for (String fieldName : objFieldNameSet) {
			objField = objMap.get(fieldName);
			descField = destMap.get(fieldName);
			if (descField != null) {
				if (objField.getType().equals(descField.getType())) {
					objField.setAccessible(true);
					descField.setAccessible(true);
					try {
						if ((isCopyNull || objField.get(src) != null) && !Modifier.isFinal(objField.getModifiers())) {
							descField.set(dest, objField.get(src));
						}
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				}
			}
		}
	}

	/**
	 * 获取该对象自己以及继承的上层对象的所有属性
	 * 
	 * @param obj
	 * @param isParentField
	 *            是否包含父类的属性
	 * @return
	 */
	public static Map<String, Field> getObjectAllField(Object obj, boolean isParentField) {
		Map<String, Field> fieldMap = new HashMap<String, Field>();
		Class<?> objCls = obj.getClass();
		while (objCls != null) {
			Field[] fields = objCls.getDeclaredFields();
			for (Field field : fields) {
				if (!fieldMap.containsKey(field.getName())) {
					fieldMap.put(field.getName(), field);
				}
			}
			if (!isParentField)
				break;
			objCls = objCls.getSuperclass();
		}
		return fieldMap;
	}

	/**
	 * 获取该对象自己以及继承的上层对象的所有属性
	 * 
	 * @param class
	 * @param isParentField
	 *            是否包含父类的属性
	 * @return
	 */
	public static Map<String, Field> getObjectAllField(Class<?> objCls, boolean isParentField) {
		Map<String, Field> fieldMap = new HashMap<String, Field>();
		while (objCls != null) {
			Field[] fields = objCls.getDeclaredFields();
			for (Field field : fields) {
				if (!fieldMap.containsKey(field.getName())) {
					fieldMap.put(field.getName(), field);
				}
			}
			if (!isParentField)
				break;
			objCls = objCls.getSuperclass();
		}
		return fieldMap;
	}

	/**
	 * 获取对象属性值
	 * 
	 * @param obj
	 * @param fieldName
	 * @return
	 */
	public static Object getObjectFieldValue(Object obj, String fieldName) {
		Class<?> cls = obj.getClass();
		try {
			Field field = cls.getField(fieldName);
			field.setAccessible(true);
			return field.get(obj);
		} catch (NoSuchFieldException e) {
			logger.error(e.getMessage(), e);
		} catch (SecurityException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	public static Object getObjectByMethodName(Object obj, String methodName) {
		Class<?> cls = obj.getClass();
		try {
			Method method = cls.getDeclaredMethod(methodName, null);
			return method.invoke(obj, null);
		} catch (NoSuchMethodException e) {
			logger.error(e.getMessage(), e);
		} catch (SecurityException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			logger.error(e.getMessage(), e);
		} catch (InvocationTargetException e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 判断对象是否为基本数据类型
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean isBaseType(Object obj) {
		try {
			Field field = obj.getClass().getField("TYPE");
			if(field == null){
				return false;
			}
			return ((Class<?>) field.get(null)).isPrimitive();
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 判断对象是否为基本数据类型
	 * 
	 * @param clazz
	 * @return
	 */
	public static boolean isBaseType(Class<?> clazz) {
		try {
			Field field = clazz.getField("TYPE");
			if(field == null){
				return false;
			}
			return ((Class<?>) field.get(null)).isPrimitive();
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 获取对象集合中某个属性的集合
	 * 
	 * @param list
	 * @param fieldName
	 * @param cls
	 * @return
	 */
	public static <T> List<T> getFieldValueList(List<?> list, String fieldName, Class<T> cls) {
		List<T> fieldValueList = new ArrayList<T>();
		if (list.size() == 0) {
			return fieldValueList;
		}
		Class<?> clazz = list.get(0).getClass();
		try {
			Field field = clazz.getDeclaredField(fieldName);
			field.setAccessible(true);
			for (Object obj : list) {
				fieldValueList.add(cls.cast(field.get(obj)));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return fieldValueList;
	}


	//将javabean实体类转为map类型，然后返回一个map类型的值
	public static Map<String, Object> beanToMap(Object obj) {
		Map<String, Object> params = new HashMap<String, Object>(0);
		try {
			PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
			PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
			for (int i = 0; i < descriptors.length; i++) {
				String name = descriptors[i].getName();
				if (!"class".equals(name)) {
					params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
	}
}
